<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2021/3/30
  Time: 16:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>layout 后台大布局 - Layui</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">

    <jsp:include page="../common/header.jsp"></jsp:include>

    <jsp:include page="../common/menu.jsp"></jsp:include>

    <div class="layui-body">
        <!-- 内容主体区域 -->
        <div style="padding: 15px;">
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
                <legend>人员列表</legend>
            </fieldset>

            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">输入框</label>
                        <div class="layui-input-inline">
                            <input type="text" name="lastName"  placeholder="请输入标题" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">开始时间</label>
                        <div class="layui-input-inline">
                            <input  name="start"  type="text" class="layui-input" id="start">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">开始时间</label>
                        <div class="layui-input-inline">
                            <input  name="end"  type="text" class="layui-input" id="end">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <div class="layui-input-inline">
                            <button class="layui-btn" lay-submit lay-filter="formEmp">查询</button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </div>
            </form>

            <div>
                <table class="layui-hide" id="test" lay-filter="test"></table>

                <script type="text/html" id="toolbarDemo">
                    <div class="layui-btn-container">
                        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
                        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
                        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
                        <button class="layui-btn layui-btn-sm" lay-event="addEmp">添加</button>
                    </div>
                </script>
                <script type="text/html" id="barDemo">
                    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                </script>
            </div>
        </div>

    </div>



    <div class="layui-footer">
        <!-- 底部固定区域 -->
        © layui.com - 底部固定区域
    </div>
</div>
<div style="padding: 20px; display: none " id="addEmpDiv">
    <form class="layui-form" lay-filter="empForm" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">lastName</label>
            <div class="layui-input-block">
                <input type="text" name="lastName"  placeholder="请输入标题" autocomplete="off" class="layui-input">
                <input type="hidden" name="id"  >
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">firstName</label>
            <div class="layui-input-block">
                <input type="text" name="firstName"  placeholder="请输入标题" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">address</label>
            <div class="layui-input-block">
                <input type="text" name="address"  placeholder="请输入标题" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">部门</label>
            <div class="layui-input-block">
                <select id="deptList" name="deptId" lay-verify="required">

                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">单选框</label>
            <div class="layui-input-block">
                <input type="radio" name="gender" value="1" title="男">
                <input type="radio" name="gender" value="0" title="女" checked>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">时间</label>
            <div class="layui-input-block">
                <input type="text" name="date"  id="date" class="layui-input" >
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="addEmp">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>

    </form>
</div>

<script src="${pageContext.request.contextPath}/layui/layui.js"></script>
<script>
    var $ = "";
    layui.use(['form','table','laydate','jquery'], function(){
        //时间控件
        var laydate = layui.laydate;
        //时间控件
        var table = layui.table;
        //表单
        var form = layui.form;

        $ = layui.$

        var index = '';

        //监听提交
        form.on('submit(formEmp)', function(data){
            // var d = JSON.stringify(data.field.lastName);
            // 表格重载
            table.reload('test', {
                where: { //设定异步数据接口的额外参数，任意设
                    lastName: data.field.lastName,
                    start: data.field.start,
                    end: data.field.end,
                }
            });

            return false;
        });
        //温馨提示：默认由前端自动合计当前行数据。从 layui 2.5.6 开始： 若接口直接返回了合计行数据，则优先读取接口合计行数据。
        //详见：https://www.layui.com/doc/modules/table.html#totalRow
        table.render({
            elem: '#test'
            ,url:'emplist'
            ,method:'post'
            ,contentType:'application/json'
            ,toolbar: '#toolbarDemo'
            ,title: '用户数据表'
            ,totalRow: true
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', title:'ID', width:80, fixed: 'left', unresize: true, sort: true, totalRowText: '合计'}
                ,{field:'lastName', title:'用户名', width:120, edit: 'text'}
                ,{field:'gender', title:'性别', width:150, edit: 'text', templet: function(res){
                        return res.gender == 1 ? "男" : "女";
                    }}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
            ]]
            ,page: true,
            limit:5,
            limits:[10, 20, 30, 40, 50]

        });

        //工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选')
                    break;
                case 'addEmp':
                    // 查询dept数据
                    getDeptList();
                    // 弹出框
                    index = layer.open({
                        type: 1,
                        title: ['添加人员', 'font-size:18px;'],
                        area: ['900px', '660px'],
                        shadeClose: false, //点击遮罩关闭
                        content: $("#addEmpDiv")
                    });
                    break;
            };
        });

        //工具条事件
        table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

            if(layEvent === 'del'){ //删除
                layer.confirm('真的删除行么', function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                });
            } else if(layEvent === 'edit'){ //编辑
                //do something
                // alert(JSON.stringify(data))
                index = layer.open({
                    type: 1,
                    title: ['修改人员', 'font-size:18px;'],
                    area: ['800px', '560px'],
                    shadeClose: false, //点击遮罩关闭
                    content: $("#addEmpDiv"),
                    success : function(layero, index) {
                        // 发送ajax获取 deptName
                        $.ajax({
                            url:'${pageContext.request.contextPath}/dept/getlist',
                            dataType:'JSON',
                            type:'get',
                            async: false,
                            success:function (d) {
                                $("#deptList").html("<option value='0'>请选择</option>");
                                $.each(d,function(index,item){
                                    var option = new Option(item.deptName,item.id);
                                    // alert(item.id + " -- " + data.deptId)
                                    if(item.id == data.deptId) {
                                        option.setAttribute("selected",'true');
                                    }
                                    $('#deptList').append(option);//往下拉菜单里添加元素
                                })
                                layui.form.render("select");//重新渲染 固定写法
                            }
                        })


                        form.val("empForm", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                            "id":data.id,
                            "lastName": data.lastName, // "name": "value"
                            "firstName": data.firstName,
                            "address":data.address,
                            "date":data.date,
                            "gender": data.gender,
                        });
                    }
                });
            }
        });


        //监听提交
        form.on('submit(addEmp)', function(data){
            // layer.msg(JSON.stringify(data.field));
            //发送ajax
            if (data.field.id != ''){
                $.ajax({
                    url:'${pageContext.request.contextPath}/employee/update',
                    dataType:'text',
                    data:JSON.stringify(data.field),
                    contentType: 'application/json',
                    type:'post',
                    success:function (data) {
                        if (data == 'true'){
                            layer.msg("修改成功");
                            layer.close(index);
                            //重载表格
                            table.reload('test');
                        }

                    }
                })
            }else {
                $.ajax({
                    url:'${pageContext.request.contextPath}/employee/insert',
                    dataType:'text',
                    data:JSON.stringify(data.field),
                    contentType: 'application/json',
                    type:'post',
                    success:function (data) {
                        if (data == 'true'){
                            layer.msg("添加成功");
                            layer.close(index);
                            //重载表格
                            table.reload('test');
                        }
                    }
                })
            }

            return false;
        });

        //执行一个laydate实例
        laydate.render({
            elem: '#start' //指定元素
        });
        laydate.render({
            elem: '#end' //指定元素
        });
        laydate.render({
            elem: '#date' //指定元素
        });



    });
    var pid = '';
    function getDeptList(){
        //发送ajax
        $.ajax({
            url:'${pageContext.request.contextPath}/dept/getlist',
            dataType:'text',
            contentType: 'javascript/json',
            type:'get',
            success:function (data) {
                var dept =  JSON.parse(data)
                var str = '<option value="0">请选择</option>';

                $.each(dept,function (){

                    str += '<option value="'+this.id+'">'+this.deptName+'</option>';

                })
                $("#deptList").html(str);
                layui.form.render("select");//重新渲染 固定写法
            }
        })
    }


</script>
</body>

</html>
